<template>
  <view class="tree-select">
    <!-- 使用原生元素模拟select -->
    <view class="select-box" @click="toggleTree">
      <text class="placeholder" v-if="!selectedLabel">{{ placeholder }}</text>
      <text class="value-text">{{ selectedLabel }}</text>
      <uni-icons v-if="showClear" type="clear" class="clear-icon" @click.stop="clearSelect" />
      <uni-icons v-else type="arrowdown" class="arrow-icon" />
    </view>

    <!-- 自定义树形弹窗 -->
    <view v-if="showTree" class="tree-popup">
      <scroll-view scroll-y class="tree-scroll">
		  <view v-if="processedData.length === 0" class="empty-tip">
		      暂无数据
		    </view>
        <tree-node v-else
          v-for="node in processedData"
          :key="node[keyField]"
          :node="node"
          :level="0"
          :props="props"
          :selected="selectedValue"
          @node-click="handleNodeClick"
        />
      </scroll-view>
    </view>
  </view>
</template>

<script>
// 树节点递归组件
import treeNode from"./treeNode.vue"

export default {
  components: { treeNode },
  props: {
    data: {
      type: Array,
      default: () => []
    },
    value: [String, Number, Array],
    props: {
      type: Object,
      default: () => ({
        label: 'label',
        children: 'children',
        value: 'value'
      })
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    multiple: Boolean,
    clearable: Boolean
  },
  data() {
    return {
      showTree: false,
      selectedValue: this.multiple ? [] : null,
      selectedLabel: ''
    }
  },
  computed: {
    keyField() {
      return this.props.value
    },
    labelField() {
      return this.props.label
    },
    childrenField() {
      return this.props.children
    },
    showClear() {
      return this.clearable && 
        (this.multiple ? this.selectedValue.length > 0 : this.selectedValue)
    },
    processedData() {
		console.log(this.deepClone(this.data));
      return this.deepClone(this.data)
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        this.selectedValue = newVal
        this.updateSelectedLabel()
      }
    }
  },
  methods: {
    toggleTree() {
      this.showTree = !this.showTree
    },

    handleNodeClick(node) {
      if (this.multiple) {
        const index = this.selectedValue.indexOf(node[this.keyField])
        index === -1 
          ? this.selectedValue.push(node[this.keyField])
          : this.selectedValue.splice(index, 1)
      } else {
		  if(!node[this.childrenField]||node[this.childrenField].length===0){
			  this.selectedValue = node[this.keyField]
			  this.showTree = false
		  }
      }
      this.$emit('node-click', this.selectedValue)
      this.updateSelectedLabel()
    },

    updateSelectedLabel() {
      if (this.multiple) {
        const labels = []
        this.findLabels(this.data, this.selectedValue, labels)
        this.selectedLabel = labels.join(', ')
      } else {
        const node = this.findNode(this.data, this.selectedValue)
        this.selectedLabel = node ? node[this.labelField] : ''
      }
    },

    findNode(data, value) {
      for (const item of data) {
        if (item[this.keyField] === value) return item
        if (item[this.childrenField]) {
          const found = this.findNode(item[this.childrenField], value)
          if (found) return found
        }
      }
      return null
    },

    findLabels(data, values, result) {
      data.forEach(item => {
        if (values.includes(item[this.keyField])) {
          result.push(item[this.labelField])
        }
        if (item[this.childrenField]) {
          this.findLabels(item[this.childrenField], values, result)
        }
      })
    },

    clearSelect() {
      this.selectedValue = this.multiple ? [] : null
      this.selectedLabel = ''
      this.$emit('input', this.selectedValue)
    },

    deepClone(obj) {
      return JSON.parse(JSON.stringify(obj))
    }
  }
}
</script>

<style lang="scss">
.tree-select {
  position: relative;
  width: 100%;

  .select-box {
    height: 90rpx;
    border: 1px solid #e5e5e5;
    border-radius: 4px;
    padding: 0 10px;
    display: flex;
    align-items: center;
    position: relative;

    .placeholder {
      color: #999;
    }

    .clear-icon, .arrow-icon {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
    }
  } // 这里缺少了闭合括号

  .tree-popup {
    position: absolute;
    top: 45px;
    left: 0;
    right: 0;
    background: #fff;
    border: 1px solid #e5e5e5;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0,0,0,.1);
    z-index: 999;

    .tree-scroll {
      max-height: 300px;
	  
	  .empty-tip {
	    padding: 20px;
	    text-align: center;
	    color: #999;
	  }
    }

    .tree-node {
      padding: 8px 10px;

      .node-content {
        display: flex;
        align-items: center;

        .arrow-icon {
          margin-right: 8px;
          transition: transform 0.3s;

          &.expanded {
            transform: rotate(180deg);
          }
        }

        .node-label {
          &.selected {
            color: #007aff;
            font-weight: bold;
          }
        }
      }

      &:hover {
        background-color: #f5f5f5;
      }
    }
  }
}
</style>